package com.ftg.learn.chapter8.pattern.singleton.thread;

/**
 * 灯
 * <p>
 * 请编写一个类，模拟灯被打开以及关闭两个功能，请尝试通过线程来完成。
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/8/3 下午3:14
 */
public class HomeWork1 {

    //共享变量   灯状态

    private static boolean lightState = false;

    private static synchronized void turnChange(){
        lightState = !lightState;
        System.out.println(Thread.currentThread().getName() + "==状态==" + lightState + "==>" + (lightState ? "开着的" : "关着的"));
    }

    public static void main(String[] args) {
       Thread t1 = new Thread(()->{
           for (int i = 0; i < 10; i++) {
               turnChange();
           }

       },"第一个线程");

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                turnChange();
            }
        },"第二个线程");

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("完成了");
    }

}
